package com.bms.utils;

public class IPUtil {
	private static final long LOW_8_BITS_MASK = 0xFFl;
	private static final long HIGH_1_BIT_MASK = 0x80000000l;

	public static boolean isInRange(long ip, long start, long mask) {
		return (ip & mask) == (start & mask);
	}
	
	public static long parseIP(String ip) {
		String[] startParts = ip.split("\\.");
		return (Long.parseLong(startParts[0]) << 24)
				+ (Long.parseLong(startParts[1]) << 16)
				+ (Long.parseLong(startParts[2]) << 8)
				+ Long.parseLong(startParts[3]);
	}

	public static String encodeIP(long ip) {
		StringBuilder ipBuilder = new StringBuilder();
		ipBuilder.append(ip >> 24 & LOW_8_BITS_MASK);
		ipBuilder.append(".");
		ipBuilder.append(ip >> 16 & LOW_8_BITS_MASK);
		ipBuilder.append(".");
		ipBuilder.append(ip >> 8 & LOW_8_BITS_MASK);
		ipBuilder.append(".");
		ipBuilder.append(ip & LOW_8_BITS_MASK);
		return ipBuilder.toString();
	}

	public static long parseMask(int mask) {
		long maskValue = 0l;
		for (int i = 0; i < mask; i++) {
			maskValue >>= 1;
			maskValue |= HIGH_1_BIT_MASK;
		}
		return maskValue;
	}

}
